<template>
  <div class="top">
    <div class="top-wrapper">
      <div class="topFlex">
        <div class="link-item" @click="toPortal()">
          <a-icon type="home" theme="filled" />
          <span>返回首页</span>
        </div>
        <div v-if="isLogin" class="link-item ML10" @click="toPortal()">
          {{ userInfo ? userInfo.userName + '，您好！' : '' }}
        </div>
        <div class="link-item">
          <span class="colorMain" @click="changeRole" v-if="isLogin && roles && roles.length > 1">【切换({{ roleCodeMap[role]
            }})】</span>
          <!-- <span class="colorMain">【 {{ isLogin ? '工作台' : '登录' }} 】</span> -->
          <span class="colorMain" @click="toBackend" v-if="isLogin">【工作台】</span>
          <div v-else>
            <span class="colorMain" @click="toPersonLogin">【采购 / 供应商登录】</span>
            <span class="colorMain" @click="toBackend">【运营登录】</span>
          </div>

        </div>
      </div>

      <div v-if="isLogin"
        style="flex: 1;display: flex;align-items: center;justify-content: flex-end;text-align: right;">
        <a-menu class="title-menu" mode="horizontal">
          <a-sub-menu v-for="(item, index) in permTree" :key="item.id" popup-class-name="title-submenu-popup ">
            <span slot="title">{{ item.permName }}<a-icon class="title-icon" type="up" /></span>
            <template v-if="item.children">
              <a-menu-item @click="menuClick(child)" v-for="(child, childIndex) in item.children" :key="child.id">
                <span>{{ child.permName }}</span>
              </a-menu-item>
            </template>
          </a-sub-menu>
        </a-menu>
        <div class="link-item logout">
          <a-icon type="poweroff" />
          <span @click="toLogin">退出</span>
        </div>
      </div>
    </div>
    <personSelect v-if="visible" :visible="visible" @ok="personOk" :submitLoading="submitLoading" @cancel="cancel">
    </personSelect>
    <a-modal :bodyStyle="{padding:'0!important'}" v-model="feedVisible" :footer="null" :width="600"
             :destroyOnClose="true" :closable="false">
      <feedModal @backModal="feedVisible=false"></feedModal>
    </a-modal>
  </div>
</template>

<script>
import storage from '@/utils/storage'
import { appConfig } from '@/config/app'
import { getLoginUrl } from '@/api/portalSetting'
import { ssoLogout, qryModulePermByRoleId } from '@/api/sso'
import { list2MenuTree } from "@/utils/func";
import personSelect from '@/components/base/personSelect'
import feedModal from '@/components/feedModal'
import { roleCodeMap } from '@/config'

export default {
  name: 'Top',
  components: { personSelect, feedModal },
  data() {
    return {
      isLogin: storage.session.get('isLogin') && storage.session.get('authToken'),
      userInfo: storage.session.get('userInfo'),
      permTree: [],
      topPermTree: storage.session.get('topPermTree') || [],
      visible: false,
      submitLoading: false,
      roles: storage.session.get('roles'),
      role: storage.session.get('role'),
      roleCodeMap,
      feedVisible: false

    }
  },
  mounted() {
    if (this.isLogin) {
      this.topPermTree.length > 0 ? this.permTree = this.topPermTree : this.getTopMenu()
    }
  },
  methods: {
    personOk(user, userList) {
      storage.session.set('role', user.id)

      let roles = userList.map(item => {
        return item.id
      })
      storage.session.set('roles', roles)
      this.role = user.id
      this.$store.commit('setRole', user.id)

      console.log(user, 'user')
      storage.session.remove('topPermTree')
      this.getTopMenu()
      this.visible = false
    },
    changeRole() {
      this.visible = true

    },
    cancel() {
      this.visible = false
    },
    menuClick(record) {
      console.log(record, 'record22')
      console.log(record.url, 'record22')
      if (record.url == 'addFeedback'){
        console.log(record, 'feedVisible')
        this.feedVisible = true
      }else {
        this.$router.push({ path: record.url, query: { id: record.id } });
      }
    },
    getTopMenu() {
      qryModulePermByRoleId({
        module: 'TOP',
        roleId: storage.session.get('role')
      }).then(res => {
        if (res.code == 0) {
          res.data = res.data.length > 0 ? res.data.filter(item => item.isCheck) : []

          const permTree = list2MenuTree(res.data, 'permId', 'pPermId', 'permName')
          storage.session.set('topPermTree', permTree)

          this.permTree = permTree
          console.log(permTree, 'permTree')
        }
      })
    },
    toBackend() {
      if (this.isLogin) {
        const roles = storage.session.get('roles')
        if (!roles) return this.$message.error('该用户暂无角色信息')
        // if (roles.length > 1) storage.session.remove('role')
        console.log('----------')
        location.href = location.origin + location.pathname + 'manage/#/'
      } else {
        location.href = location.origin + location.pathname + '#/login'
      }
    },
    async toPersonLogin() {
      let res = await getLoginUrl()
      let { portalBackendUrl } = res.data || {};
      let returnUrl = location.origin + location.pathname + this.escapeUrl('#/callbackSso?gldtoken=${userToken}&app=gyszszx')
      const url = portalBackendUrl + `?redirect=${returnUrl}&target=outside`
      window.open(url, '_self', 'noopener=yes,noreferrer=yes')
    },
    escapeUrl(url) {
      let escUrl = encodeURIComponent(url);
      return escUrl
    },
    async toLogin() {
      const token = storage.session.get('gldToken')
      let logout = gt => {
        this.removeAll()
        if (!gt) storage.session.remove('gldToken')

        // this.toGldPath('loginUrl')
        location.href = location.origin + location.pathname + '#/login'
      }
      if (!token) return logout(1)
      try {
        await ssoLogout({ token })
      } catch (e) {

      }
      logout()
    },
    removeAll() {
      storage.session.remove('isLogin')
      storage.session.remove('authToken')
      storage.session.remove('userInfo')
      storage.session.remove('role')
      storage.session.remove('topPermTree')

      storage.session.remove('roles')
      storage.session.remove('wallet')
      // this.toGldPath('loginUrl')
    }
  }
}
</script>

<style scoped lang="scss">
$width: 1200px;
$mainColor: #0078FE;

.w1200 {
  width: $width;
  margin: 0 auto;
}

.title-menu {
  line-height: 36px;
  background: transparent;
  border: none;
  height: 36px;
  width: 100%;

  /deep/ .ant-menu-item {
    top: 0;
    padding: 0 !important;
    border-bottom: none;
  }

  /deep/ .ant-menu-submenu {
    top: 0;
    border-bottom: none !important;
    margin-right: 20px;
  }

  /deep/ .ant-menu-submenu-selected {
    border-bottom: none !important;
  }

  /deep/ .ant-menu-submenu:hover {
    border-bottom: none !important;
  }

  /deep/ .ant-menu-item-selected {
    border-bottom: none !important;
  }

  /deep/ .ant-menu-item:hover {
    border-bottom: none !important;
  }

  /deep/ .ant-menu-submenu-title {
    padding: 0 !important;

    .title-icon {
      transform: rotate(0deg);
      transition: transform 0.3s;
      font-size: 12px;
      margin-right: 0 !important;
      margin-left: 4px;
    }

    &:hover {
      .title-icon {
        transform: rotate(180deg);
        transition: transform 0.3s;
      }
    }
  }
}

.undo-count {
  transform: scale(0.6);
  position: absolute;
  right: -12px;
  top: -8px;
}

.colorMain {
  color: $mainColor !important;
}

.top {
  width: 100%;
  height: 36px;
  background: #FAFAFA;
  font-family: PingFangSC-Regular, sans-serif;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #646464;

  .top-wrapper {
    @extend .w1200;
    display: flex;

    .topFlex {
      display: flex;
      align-items: center;
    }

    .link-item {
      display: flex;
      align-items: center;
      cursor: pointer;

      &.logout {
        width: 100px;
      }

      i {
        font-size: 16px;
        color: #909090;
      }

      span {
        color: #646464;
        margin-left: 6px;
      }

      &:hover {
        span {
          color: $mainColor;
        }
      }

      &.split {
        &::after {
          content: '';
          height: 15px;
          width: 1px;
          background: #c7c7c7;
          margin: 0 14px;
        }

        &:hover {
          color: $mainColor !important;

          i {
            color: $mainColor !important;
          }
        }
      }

      &.logout {
        &:hover {
          i {
            color: $mainColor !important;
          }
        }
      }
    }

    button {
      color: $mainColor;
    }
  }
}
</style>
